package com.dylan.历史.java8.其他;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by Dylan on 2018/7/30.
 */
public class 集合 {

    public static void main(String[] args) {
        Map<Integer, List<String>> map = getWords().collect(Collectors.groupingBy(String::length));

        // 替换,只有存在时才会替换成功
        map.replace(12, Arrays.asList("asdf", "sdfsdf"));

        // 全部替换,可以根据key和value进行处理
        map.replaceAll((length, wordList) -> {
//            if (length > 3) {
//                return Collections.emptyList();
//            }
            return wordList;
        });

        // 删除,当key和value都相同时才删除
        map.remove(12, Arrays.asList("asdf", "sdfsdf"));

        // 当值为null时才成功
        map.putIfAbsent(14, Arrays.asList("asdf", "sdfsdf")); // 返回null

        // 通过映射计算新value,并保存.如果新value为null,则删除旧的键值对
        map.compute(12, (length, wordList) -> Arrays.asList("asdf", "sdfsdf"));

        // 保存新值,如果旧值存在,则进行处理再保存
        map.merge(14, Arrays.asList("asdf", "sdfsdf"), (length, wordList) -> Arrays.asList("asdf", "sdfsdf"));

//        map.forEach((length, wordList) -> {
//            System.out.println(length + "->" + wordList);
//        });


        // 删除符合条件的元素
        List<String> list = Stream.of("asdf", "sdfsdf").collect(Collectors.toList());
        list.removeIf(s -> s.length() == 4);
        System.out.println(list);
    }

    private static Stream<String> getWords() {
        return Pattern.compile("[\\P{L}]+").splitAsStream("Ramesses VI was the fifth ruler of the Twentieth Dynasty of Egypt. He succeeded Ramesses V and reigned for about eight years in the mid-to-late 12th century BC before dying in his forties. Egypt lost control of its last strongholds in Canaan around the time of his reign. The pharaoh's power waned in Upper Egypt during his rule, while the high priest of Amun, Ramessesnakht, was turning Thebes in Upper Egypt into the religious capital and a second center of power on par with Pi-Ramesses in Lower Egypt, where the pharaoh resided. He was fond of cult statues of himself; more are known to portray him than any other Twentieth-Dynasty king after his father, Ramesses III. He usurped KV9, a tomb in the Valley of the Kings planned by and for Ramesses V, and had it enlarged and redecorated for himself. His mummy lay untouched for fewer than 20 years before pillagers damaged it.");
    }
}
